<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Qmzs
 *
 * @author dragon.hu @2016.2.25
 */
require_once 'BaseChannel.php';

//全民助手
class Qmzs implements BaseChannel 
{
	static private $encryptDataKey= "fHu2AjQsvjTepsmhF0Pj1Q==";
	
	function __construct() 
	{
		//echo "construct";
	}

	//put your code here
	function android($data) 
	{
		$paymentKey="nQMGxKxiLlasJsCMAc6w0Q=="; //MD5key
		$ret = $this->paymentCallBack($paymentKey, ANDROID);
		echo $ret;
	}

	function ios($data) 
	{
		$paymentKey=""; //秘钥
		$ret = $this->paymentCallBack($paymentKey, IOS);
		echo $ret;
	}

	function paymentCallBack($paymentKey, $platform)
	{
		/*3DESKey 用于报文包体加密
		对应文档中的secretKey：
		fHu2AjQsvjTepsmhF0Pj1Q==
		signKey 用于报文签名
		对应文档中的MD5Key：
		nQMGxKxiLlasJsCMAc6w0Q==*/
		$orderLog = new ChargeOrder();
		$orderLog->log("qmzs", $_POST);
		
		$request = file_get_contents("php://input");
		$request = str_replace('\x22', '"', $request);
		if (empty($request)) 
		{
			$orderLog->log("qmzs", "POST获取数据为空");
			return;
		}
		else
		{
			$orderLog->log("qmzs", $request);
		}
		
		$getdata = json_decode($request, true);
		
		$id = $getdata['id'];
		$ver = $getdata['ver'];
		$devCode = $getdata['devCode'];
		$actionId = $getdata['actionId'];
		$data = $getdata['data'];
		$sign = $getdata['sign'];
		
		/*签名内容是指外层数据包中，除sign以外的各字段名及其字段值的拼接，字段名与字段值之间使用等号（=）连接。拼接时需对字段名排序，排序方式是按字段名进行升序排列。
		注意：签名内容不应包含“&”符号，拼接签名内容时需把“&”符号剔除。计算MD5签名时，取签名内容的字节时，应以UTF-8编码取字符串的字节值。*/
		$mysign = "actionId=".$actionId."data=".$data."devCode=".$devCode."id=".$id."ver=".$ver.$paymentKey;		
		
		/*$gameId = $getdata['gameInfo']['gameId'];
		
		$accountId = $getdata['payRet']['accountId'];
		$qmOrderId = $getdata['payRet']['qmOrderId'];
		$billId = $getdata['payRet']['billId'];
		$amount = $getdata['payRet']['amount'];
		$callbackInfo = $getdata['payRet']['callbackInfo'];
		$successFlag = $getdata['payRet']['successFlag'];
		$payTime = $getdata['payRet']['payTime'];
		$payFee = $getdata['payRet']['payFee'];
		$gameData01 = $getdata['payRet']['gameData01'];
		$gameData02 = $getdata['payRet']['gameData02'];
		$gameData03 = $getdata['payRet']['gameData03'];
		$gameData04 = $getdata['payRet']['gameData04'];
		$gameData05 = $getdata['payRet']['gameData05'];
		$gameData06 = $getdata['payRet']['gameData06'];
		
		$dataA = $getdata['extData']['dataA'];
		$dataB = $getdata['extData']['dataB'];
		$dataC = $getdata['extData']['dataC'];
		$dataD = $getdata['extData']['dataD'];
		$dataE = $getdata['extData']['dataE'];
		$dataF = $getdata['extData']['dataF'];*/
		
		$response = array();
		$response['id'] = Qmzs::getMillisecond();
		$response['ver'] = $ver;
		$response['devCode'] = $devCode;
		$response['actionId'] = $actionId;
		$responseData = array(
				'state' => array( "code" => 2000, "msg" => "SUCCESS"),
		);
		$response['data'] = $this->encrypt(json_encode($responseData));
		$response['sign'] = Qmzs::getSign($response, $paymentKey);
		
		if($sign == md5($mysign))
		{ //验证通过
			 
			//解析data中的数据
			$resData = Qmzs::decrypt($data);
			$resData = json_decode($resData, true);
			//var_dump($resData);
			//exit();
			$tmpstatus = STATUS_SUCCESS;
			if ($resData['payRet']['successFlag'] != '200')
			{
				//var_dump($resData['payRet']['successFlag']);
				$tmpstatus = STATUS_FAILD;
			}
			
			if(false == $orderLog->recordOrder($tmpstatus, $resData['payRet']['amount'], $resData['payRet']['billId'], "qmzs", $platform,$resData['payRet']['qmOrderId']))
			{
				//$responseData['state']['code'] = 0;
				//$responseData['state']['msg'] = 'failed';
				//$tmpdata = json_encode($responseData);
				$orderLog->log("qmzs",array("order"=>$resData['payRet']['billId'],"money"=>$resData['payRet']['amount'],"serverresult"=>"faild"));
			}else 
			{
				//支付成功
				//$responseData['state']['code'] = 2000;
				//$responseData['state']['msg'] = 'success';
				$orderLog->log("qmzs",array("order"=>$resData['payRet']['billId'],"money"=>$resData['payRet']['amount'],"serverresult"=>"success"));
			}
			 
		} else {
			//"$sig验证失败"
			//$responseData['state']['code'] = 1;
			//$responseData['state']['msg'] = 'sign error';
			$orderLog->log("qmzs"," sign verify failed");
		}
		$ret = json_encode($response);
		return $ret;
	}
	
	public static function decrypt($value)
	{
		$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		mcrypt_generic_init($td, self::$encryptDataKey, $iv);
		$ret = trim(mdecrypt_generic($td, base64_decode($value)));
		$ret = Qmzs::UnPaddingPKCS7($ret);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		return $ret;
	}
	
	public static function UnPaddingPKCS7($text)
	{
		$pad = ord($text{strlen($text) - 1});
		if ($pad > strlen($text)) {
			return false;
		}
		if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
			return false;
		}
		return substr($text, 0, -1 * $pad);
	}
	
	/**
	 *加密
	 * @param <type> $value
	 * @return <type>
	 */
	public function encrypt($value)
	{
		$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		$value = Qmzs::PaddingPKCS7($value);
		mcrypt_generic_init($td, self::$encryptDataKey, $iv);
		$ret = base64_encode(mcrypt_generic($td, $value));
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		return $ret;
	}
	
	public static function PaddingPKCS7($data)
	{
		$block_size = mcrypt_get_block_size('tripledes', 'ecb');
		$padding_char = $block_size - (strlen($data) % $block_size);
		$data .= str_repeat(chr($padding_char), $padding_char);
		return $data;
	}
	
	/**
	 * 获取毫秒级的时间参数
	 */
	public static function getMillisecond() {
		$time = explode(" ", microtime());
		$time = $time[1] . ($time[0] * 1000);
		$time2 = explode(".", $time);
		$time = $time2[0];
		return $time;
	}
	
	/**
	 * 按字母排序$params数组d的键,返回键.值的加密内容
	 * @param jsonPackage 业务数据
	 */
	public static function getSign($jsonPackage, $paymentkey) {
		ksort($jsonPackage);
		$tmp = '';
		foreach ($jsonPackage as $key => $val) {
			if ($key == "dataStr" || $key == "sign") {
				continue;
			}
			$tmp = $tmp . $key . '=' . $val;
		}
		$sign = $tmp . $paymentkey;
		$sign = strtolower(md5($tmp . $paymentkey));
		return $sign;
	}
}